package com.android.canvasproject.model.listeners;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;

import com.android.canvasproject.R;
import com.android.canvasproject.model.dao.ProviderDaoOpenHelper;
import com.android.canvasproject.model.entity.ColorEnum;
import com.android.canvasproject.model.entity.Postit;
import com.android.canvasproject.view.utils.ComponentViewUtil;
import com.android.canvasproject.view.utils.ConstantsAction;

public class PostitListener implements OnLongClickListener, OnClickListener, OnTouchListener {
	
	private RelativeLayout canvasModelProject;
	private Activity activity;
	private static float x;
	private static float y;

	public PostitListener(Context ctx) {
		activity = (Activity) ctx;
		canvasModelProject = (RelativeLayout) activity.findViewById(R.id.project_model_canvas);
		canvasModelProject.setOnDragListener(new PostitInternal(activity));
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			x = event.getX() - 64f;
			y = event.getY() - 64f;

		default:
			return false;
		}
	}

	@Override
	public void onClick(View v) {
		if(activity.getActionBar().isShowing())
			activity.getActionBar().hide();
		else
			activity.getActionBar().show();
	}

	@Override
	public boolean onLongClick(View v) {
		ProviderDaoOpenHelper provider = new ProviderDaoOpenHelper(activity);

		try {
			Postit p = new Postit();
//			p.setTitle("Título do postit que será exibido no quadro do Canvas.");
			p.setTitle(" ");
			p.setDescription("");
			p.setPositionX(x);
			p.setPositionY(y);
			p.setColor(ColorEnum.COLOR_YELLOW);
			p.setSponsor(1); //TODO ALTERAR APÓS DEFINIÇÃO DO USUARIO LOCAL

			Integer canvas = (Integer) (canvasModelProject.getTag() == null ? null : canvasModelProject.getTag());
			p.setCanvas(canvas);

			ContentValues values = new ContentValues();
			values.put("title", p.getTitle());
			values.put("description", p.getDescription());
			values.put("position_x", p.getPositionX());
			values.put("position_y", p.getPositionY());
			values.put("color", p.getColor().ordinal());
			values.put("id_person_sponsor", 1);
			values.put("id_canvas", p.getCanvas());

			p.setId(provider.save(Postit.PostitDao.TB_POSTIT, values));
			ComponentViewUtil.createNewPostit(activity, x, y, canvasModelProject, p);

		} catch (SQLException e) {
			Log.e(PostitListener.class.getName(), ConstantsAction.Database.INSERT, e);

		} finally {
			provider.cleanup();
		}

		return true;
	}
}